<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>火箭返回顶部</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      .box {
        width: 100%;
        height: 3000px;
        background-image: linear-gradient(skyblue, pink);
      }

      .rocket {
        width: 148px;
        height: 250px;
        background-image: url("./rocet.png");
        /* 
        火箭盒子固定在页面底部
        */
        position: fixed;
        bottom: 0;
        right: 0;
      }

      .active {
        animation: fire 0.3s infinite steps(4);
      }
      /* hover显示第二张图片 */
      .rocket:hover {
        background-position: -148px 0;
        cursor: pointer;
      }
      /* 动画效果为后面四张图片 */
      @keyframes fire {
        0% {
          background-position: -296px 0;
        }

        100% {
          background-position: -892px 0;
        }
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="rocket"></div>
    </div>
    <script>
     
      //获取火箭盒子
      let rocket = document.querySelector(".rocket");
      let rocket_distance; //火箭距离
      let rocket_v; //火箭速度
      let bars_distance; //滚动条距离
      let bars_v; //滚动条速度
      //监听整个页面滚动条事件
      document.addEventListener("scroll", function () {
        if (document.documentElement.scrollTop > 800) {
          rocket.style.display = "block";
        }
      });
      rocket.addEventListener("click", () => {
        //点击后添加喷火样式
        rocket.classList.add("active");
        //火箭路程
        rocket_distance = rocket.offsetTop + 250;
        //火箭速度
        rocket_v = rocket_distance / 50;
        //滚动条距离
        bars_distance = document.documentElement.scrollTop;
        //滚动条速度
        bars_v = bars_distance / 50;
        let timer = setInterval(function () {
          document.documentElement.scrollTop -= bars_v;
          rocket.style.top = rocket.offsetTop - rocket_v + "px";
          //滚动到顶部时消除火箭喷火样式并让火箭隐藏
          if (document.documentElement.scrollTop == 0) {
            clearInterval(timer);
            rocket.style.top = "";
            rocket.classList.remove("active");
            rocket.style.display = "none";
          }
        }, 20);
      });
    </script>
  </body>
</html>